import React, { Component } from 'react';
import TheTable from "@/components/TheTable"
import TheButton from '../../components/TheButton';
import ThePagination from '../../components/ThePagination';
import { Button, Form, Input, Modal, Space, DatePicker, Select } from "antd";
import { apiCameraBindingPage, apiCameraBindingAdd, apiCameraBindingEdit, apiCameraBindingDel, apiCameraBindingView, apiStoreCameraList } from '@/request/camera'
import { apiGetOrderGetCameraOrderInfo } from '@/request/order'
import { phoneReg } from '@/utils/regexp'
const { Option } = Select
export default class CameraAllot extends Component {
  formRef = React.createRef()
  constructor() {
    super()
    this.state = {
      columns: [{
        title: "用户手机号",
        dataIndex: "memberMobile",
        key: "memberMobile",
      },
      {
        title: "服务订单",
        dataIndex: "serviceName",
        key: "serviceName",
      },
      {
        title: "摄像头名称",
        dataIndex: "cameraName",
        key: "cameraName",
      },
      {
        title: "操作",
        render: (text) => {
          return <div>
            <TheButton hasPermi={['camera:allot:edit']} onClick={() => this.edit(text.cameraBindingId)}>编辑</TheButton>
            <TheButton hasPermi={['camera:allot:delete']} onClick={() => this.del(text.cameraBindingId)}>删除</TheButton>
          </div>
        }
      }
      ],
      dataSource: [],
      isModalVisible: false,
      pageNo: 1, pageSize: 10, total: 0,
      modalTitle: '新增',
      cameraList: [],
      serviceList: [],
      cameraBindingId: '',
      cameraId: '',
      memberMobile: '',
      loading: false,
    }
  }
  componentDidMount() {
    this.getData()
    this.getCameraList()
  }
  async getCameraList() {
    let res = await apiStoreCameraList()
    if (res.code === 0) {
      this.setState({
        cameraList: res.data
      })
    }
  }
  async getServiceList(memberMobile, cb) {
    let res = await apiGetOrderGetCameraOrderInfo({ memberMobile })
    if (res.code === 0) {
      let { serviceList } = this.state
      serviceList = [{
        orderId: "-1",
        serviceName: '外部渠道订单'
      }].concat(res.data)
      this.setState({
        serviceList
      }, () => {
        cb && cb()
      })
    }
  }
  async getData() {
    let res = await apiCameraBindingPage({ pageNo: this.state.pageNo, pageSize: this.state.pageSize, cameraId: this.state.cameraId, memberMobile: this.state.memberMobile })
    if (res.code === 0) {
      this.setState({
        dataSource: res.data,
        total: res.totalCount
      })
    }
  }
  add() {
    this.setState({
      isModalVisible: true,
      cameraBindingId: '',
      modalTitle: '新增',
      serviceList: [{
        orderId: '-1',
        serviceName: '外部渠道订单'
      }]

    }, () => this.resetForm())
  }
  edit(cameraBindingId) {
    this.setState({
      isModalVisible: true,
      cameraBindingId,
      modalTitle: '编辑',
      serviceList: []
    }, async () => {
      let res = await apiCameraBindingView({ cameraBindingId })
      if (res.code === 0) {
        await this.getServiceList(res.data.memberMobile, () => {
          this.formRef.current.setFieldsValue({
            orderId: res.data.orderId,
            memberMobile: res.data.memberMobile,
            cameraId: res.data.cameraId,
          })
        })
      }
    })
  }
  async del(cameraBindingId) {
    Modal.confirm({
      title: '提示',
      content: '是否确认删除？',
      onOk: async () => {
        let res = await apiCameraBindingDel({ cameraBindingId })
        if (res.code === 0) {
          this.setState({
            isModalVisible: false,
            cameraId: '',
            pageNo: 1
          }, () => this.getData())
        }
      },
      onCancel() {
      },
    });

  }
  handleOk = () => {
    this.formRef.current.validateFields().then(async values => {
      this.setState({
        loading: true
      })
      let res;
      if (this.state.cameraBindingId) {
        res = await apiCameraBindingEdit({ ...values, cameraBindingId: this.state.cameraBindingId, cameraType: values.orderId === "-1" ? 2 : 1 })

      } else {
        res = await apiCameraBindingAdd({ ...values, cameraType: values.orderId === "-1" ? 2 : 1 })
      }
      if (res.code === 0) {
        this.setState({
          isModalVisible: false,
          pageNo: 1, cameraBindingId: '',
          loading: false
        }, () => {
          this.getData()
        })
      } else {
        this.setState({
          loading: false
        })
      }
    })

  }
  handleCancel = () => {
    this.setState({
      isModalVisible: false,
      cameraBindingId: ''
    })
  }
  resetForm() {
    this.formRef.current.resetFields();
  }
  pageChange = (e) => {
    this.setState({
      pageNo: e
    }, () => {
      this.getData()
    })
  }
  telChange = (e) => {
    if (phoneReg.test(e.target.value)) {
      this.getServiceList(e.target.value)
    }
  }
  onFinish = (values) => {
    this.setState({
      cameraId: values.cameraId ? values.cameraId : '',
      memberMobile: values.memberMobile ? values.memberMobile : '',
    }, () => this.getData())

  }
  render() {
    let { columns, dataSource, isModalVisible, pageNo, pageSize, total, modalTitle, cameraList, serviceList, loading } = this.state
    return (
      <div className='p-layout-box '>
        <div style={{ marginBottom: 20 }}>
          <Form
            layout={'inline'}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="cameraId"
            >
              <Select allowClear placeholder="摄像头名称"
                style={{ width: 200 }}
              >
                {
                  cameraList.length > 0 && cameraList.map(item => {
                    return (
                      <Option key={item.cameraId} value={item.cameraId}>{item.cameraName}</Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
            {/* <Form.Item
                            name="memberMobile"
                        >
                            <Input placeholder='用户手机号'></Input>
                        </Form.Item> */}
            <Form.Item
            >
              <Button type='primary' htmlType='submit'>搜索</Button>
              <TheButton hasPermi={['camera:allot:add']} type="default" size="middle" onClick={() => this.add()} >新增</TheButton>
            </Form.Item>

          </Form>

        </div>
        <TheTable columns={columns} dataSource={dataSource} />
        <ThePagination pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}></ThePagination>
        <Modal title={modalTitle} visible={isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel} confirmLoading={loading} >
          <Form
            ref={this.formRef}
            name="basic"
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 18,
            }}
            autoComplete="off"
          >
            <Form.Item
              label="用户手机号"
              name="memberMobile"
              rules={[
                {
                  required: true,
                  message: '请输入用户手机号！',

                },
                {
                  pattern: phoneReg,
                  message: '请输入正确得用户手机号！',
                },
              ]}

            >
              <Input onChange={this.telChange} maxLength={11} />
            </Form.Item>
            <Form.Item
              label="请选择服务"
              name="orderId"
              rules={[
                {
                  required: true,
                  message: '请选择服务订单！',
                },
              ]}
            >
              <Select allowClear
              >
                {
                  serviceList.map(item => {
                    return (
                      <Option key={item.orderId} value={item.orderId}>{item.serviceName}</Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
            <Form.Item
              label="摄像头名称"
              name="cameraId"
              rules={[
                {
                  required: true,
                  message: '请选择摄像头名称！',
                },
              ]}
            >
              <Select allowClear
              >
                {
                  cameraList.length > 0 && cameraList.map(item => {
                    return (
                      <Option key={item.cameraId} value={item.cameraId}>{item.cameraName}</Option>
                    )
                  })
                }
              </Select>
            </Form.Item>


          </Form>
        </Modal>
      </div>
    );
  }
}
